import React, { useState, useEffect } from 'react';
import { NavBar, List, Button, ImageUploader, Toast, Loading, Mask, Ellipsis } from 'antd-mobile';
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import { useNavigate, useLocation } from 'react-router-dom';
import Cookies from 'js-cookie';
import { InbizIcon, getToken, getPageString, jumpToLogin } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';

import { UploadAppThumb, GetUserInfoByToken, WebCore } from '../service';
import styles from '../style.less';
const { routerPrefix, tokenName } = InbizConfig
const Item = List.Item;

interface Props {
  mobileconfigList: {
    icon: {
      type: string;
    };
    title: string;
    linkAddress: string;
    page: string;
    id: string;
    externalAddress: boolean;
    hide: boolean;
    isDel: boolean;
    isHide: boolean;
    isEdit: boolean;
    isSelfPage?: boolean;
  }[];
  text: string;
  className: string;
  senior?: {};
  userInfo: {
    Name: string;
    Gender: number;
    Email: string;
    MainDepartmentName: string;
    Mobile: string;
    IdentityId: number;
  };
  showExit: 'true' | 'false';
  title: {
    status: boolean;
    value: string;
  }
  $userInfo: (arg: any) => {};
  emit?: () => void
}

/**
 * InbizInfomation 组件
 */
const Infomation: React.FC<Props> = (props) => {
  const history = useNavigate()
  const { mobileconfigList, userInfo, $userInfo, showExit, title } = props || {};
  const [imageUrl, $imageUrl] = useState('');
  const [loading, $loading] = useState(false);
  const [fileList, $fileList] = useState<ImageUploadItem[]>();
  const location = useLocation();
  const token = getToken();
  useEffect(() => {
    if (userInfo) {
      $imageUrl(
        `${process.env.NODE_ENV == 'production' ? '' : InbizConfig.HOST
        }/Imagetype/GetUserAvatar?token=${token}&userId=${userInfo.IdentityId
        }&r=${Math.random()}`,
      );
    } else {
      $imageUrl('/resource/images/bpic24364.jpg');
    }
  }, [userInfo]);

  const beforeUpload = (file: any) => {
    $loading(true)
    if (file.size > 1024 * 1024 * 10) {
      Toast.show({
        content: getMessage('personalInfo.topsTenM'),
      });
      $loading(false)
      return false;
    }
    return file;
  };
  // 更换头像点击事件
  const onUpload = async (file: any): Promise<any> => {
    const url = URL.createObjectURL(file);
    // const formData = new FormData();
    // formData.append('file', file, file.name);
    function image2Base64(img: any) {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(img, 0, 0, img.width, img.height);
      const dataURL = canvas.toDataURL('image/png');
      return dataURL;
    }

    function getImgBase64() {
      const img1 = new Image();
      img1.src = url;
      img1.onload = function () {
        const base64 = image2Base64(img1);

        UploadAppThumb({
          imgX: 0,
          imgY: 0,
          imgWidth: img1.width,
          imgHeight: img1.height,
          resetChoose: true,
          mainImgPath: base64,
        }).then((res) => {
          $loading(false)
          GetUserInfoByToken({ token }).then((res: any) => {
            $userInfo(res.data);
          })
        }).catch((e) => {
          Toast.show({
            content: getMessage('personalInfo.requestTimeOut'),
          });
          $loading(false)
        })
      };
    }
    getImgBase64();
    return {
      url,
    };
    // await setTimeout(() => {
    //   return {
    //     url: URL.createObjectURL(file),
    //   };
    // }, 2000);
  };

  const signout = () => {
    let params = {
      module: 'OrgnizationManager',
      fun: 'UserLogout',
    };
    WebCore(params).then((res: any) => {
      if (res.result == 0) {
        Cookies.remove(tokenName, { path: '/' });
        jumpToLogin(res?.loginurl || '/api/auth/login');
        return;
      }
    })
  };

  return (
    <div className={`${styles.InbizInfomation}`} style={{ position: 'relative' }}>
      {/* <div className={styles.headerTitle}>
        <FormattedMessage id="page.title" />
      </div> */}
      <Mask visible={loading} onMaskClick={() => null} opacity="thin">
        <div className={styles.overlayContent}>
          <Loading color="white" />
        </div>
      </Mask>
      <NavBar back={null}>
        {
          title?.status === false ? null :
            <span style={{ fontSize: 16, color: 'var(--inbiz-color-heading)' }}>
              <TextWidget>{title.value}</TextWidget>
            </span>
        }
      </NavBar>
      <div className={styles.Header}>
        <div
          className={styles.picture}
          style={{
            backgroundImage: `url(${imageUrl})`,
            backgroundRepeat: `no-repeat`,
            backgroundSize: 'cover',
          }}
        >
          <ImageUploader
            upload={onUpload}
            beforeUpload={beforeUpload}
            value={fileList}
            onChange={$fileList}
            accept="image/gif,image/jpeg,image/jpg,image/png"
          >
            {/* 参数children不生效? */}
            <span className={styles.upload} />
          </ImageUploader>
        </div>
        <div className={styles.userName}>
          <span>{userInfo?.Name || getMessage('personalInfo.userName')}</span>
        </div>
      </div>
      <List className={styles.InfoList}>
        {mobileconfigList.map(
          (item, index) =>
            !item.hide && (
              <Item
                className={styles.InfoItem}
                prefix={
                  <InbizIcon
                    type={item.icon?.type}
                    style={{
                      fontSize: `${item.icon?.size || 18}px`,
                      color:
                        item.icon?.color == '#aaa' || item.icon?.color == '#000'
                          ? 'val(--inbiz-color-heading)'
                          : item.icon?.color,
                    }}
                  />
                }
                onClick={() => {
                  if (item?.externalAddress) {
                    window.location.href = item.linkAddress;
                  } else if (item.page && item.isSelfPage) {
                    history({
                      pathname: `${location.pathname}/${item.page}`,
                      search: 'type=person'
                    });

                  } else if (item.page) {
                    const pageRoute = item.page.split(',')[0];
                    history({
                      pathname: `${routerPrefix}${pageRoute}`,
                    });
                  } else {
                    Toast.show(getMessage('personalInfo.setPage'));
                  }
                }}
                key={`infomation-${index}`}
              >
                <span style={{ fontSize: 16 }}>
                  <TextWidget>{item.title}</TextWidget>
                </span>
              </Item>
            ),
        )}
      </List>
      {
        showExit === 'false' ? null :
          <div className={styles.logout}>
            <Button
              style={{ background: '#f25b43', borderRadius: '22px', color: '#fff', fontSize: 14, padding: '7px 20px' }}
              onClick={signout}
            >
              <TextWidget>personalInfo.loginOut</TextWidget>
            </Button>
          </div>
      }
    </div>
  );
};

export default Infomation;
